<template>
    <div>
        <Card :bordered="false" dis-hover class="ivu-mt">
            <Button type="primary" @click="handleOpenCreate">新增</Button>
            <Table size="small" :columns="columns" :loading="loading" :data="dataList" class="ivu-mt-16">
                <template slot-scope="{ row }" slot="status">
                    <Button v-if="row.status ==='1'" type="success" size="small" @click="handleChangeStatus(row)">启用</Button>
                    <Button v-if="row.status ==='0'" type="error" size="small" @click="handleChangeStatus(row)">停用</Button>
                </template>
                <template slot-scope="{ row }" slot="count">
                    <a class="shou">{{ row.count_member }}</a>
                </template>
                <template slot-scope="{ row, index }" v-if="row.is_edit === 0 ? false : true" slot="operation">
                    <a @click="handleUpdata(index)">编辑</a>
                    <Divider type="vertical" />
                    <a @click="handleDeleteItem(row)">删除</a>
                </template>
            </Table>
            <div class="ivu-mt ivu-text-center">
                <Page
                        :total="page.total"
                        :current.sync="page.page"
                        show-total
                        show-elevator
                        :page-size="page.pageSize"
                        @on-change="handleChangePage"
                        :page-size-opts="pageOpts"
                        show-sizer transfer
                        @on-page-size-change="changePageSize"
                />
            </div>
        </Card>
        <Modal v-model="showCreate" :title="title" :loading="creating" :mask-closable= "false" @on-ok="handleSubmit">
            <Form :model="formData" ref="create" :rules="createRules"  :label-width="80">
                <FormItem label="名称" required prop="name">
                    <Input v-model="formData.name" placeholder="请输入" clearable></Input>
                </FormItem>
                <FormItem label="说明" prop="desc">
                    <Input v-model="formData.desc" placeholder="请输入" clearable></Input>
                </FormItem>
                <FormItem label="状态">
                    <i-switch v-model="formData.status">
                        <span slot="open">On</span>
                        <span slot="close">Off</span>
                    </i-switch>
                </FormItem>
                <FormItem label="权限">
                    <Tree
                            class="role-permission-modal"
                            ref="roleTree"
                            :data="rolePermissionList"
                            multiple
                            show-checkbox
                            @on-check-change="handleSelectRoles"
                    ></Tree>
                </FormItem>
            </Form>
        </Modal>
    </div>
</template>

<script>
    import { mapState } from 'vuex';
    import {
        GetSystemList,
        CreateRole,
        DeleteRole,
        UpdateRole,
        ChangeRoleStatus,
        GetRolePermission
    } from '@/api/setting';
    export default {
        name: 'diagnosis',
        computed: {
            ...mapState('admin/menu', ['project', 'currentProject'])
        },
        data () {
            return {
                indeterminate: true,
                pageOpts: [10, 20, 30, 50],
                checkAll: false,
                checkAllGroup: ['导医模块', '患者模块'],
                showCreate: false,
                updateIndex: 0,
                title: '',
                creating: true,
                loading: false,
                // 权限列表
                rolePermissionList: [],
                // 设置权限的集合
                selectPermissonList: [],
                formData: {
                    name: '',
                    desc: '',
                    status: true
                },
                createRules: {
                    name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
                },
                page: {
                    page: 1,
                    pageSize: 10,
                    total: 0
                },
                columns: [
                    {
                        title: '名称',
                        key: 'name'
                    },
                    {
                        title: '人数',
                        slot: 'count'
                    },
                    {
                        title: '说明',
                        key: 'desc'
                    },
                    {
                        title: '状态',
                        slot: 'status'
                    },
                    {
                        title: '操作',
                        slot: 'operation'
                    }
                ],
                dataList: []
            }
        },
        mounted () {
            this.getData();
        },
        methods: {
            // 获取角色列表
            getData () {
                this.loading = true;
                GetSystemList({
                    pageSize: this.page.pageSize,
                    page: this.page.page
                }).then(res => {
                    this.dataList = res.list;
                    this.page.total = res.total;
                }).finally(() => {
                    this.loading = false
                })
            },
            handleLookPeople (id) {
                window.localStorage.setItem('roleID', id)
                this.$router.push('/setting/power/personnel')
            },
            // 删除角色
            handleDeleteItem (row) {
                this.$Modal.confirm({
                    title: '删除角色',
                    content: '确定删除当前角色?',
                    onOk: () => {
                        DeleteRole({
                            id: row.id
                        }).then(() => {
                            this.$Message.success('删除成功')
                            this.getData()
                        })
                    }
                });
            },
            // 点击新增
            handleOpenCreate () {
                this.updateIndex = -1
                this.title = '新增'
                this.$nextTick(() => {
                    this.$refs['create'].resetFields();
                })
                this.roleList(0)
            },
            // 切换状态
            handleChangeStatus (row) {
                this.$Modal.confirm({
                    title: '切换角色状态',
                    content: '确定' + (row.status === '1' ? '停用' : '启用') + '当前角色?',
                    onOk: () => {
                        ChangeRoleStatus({
                            id: row.id,
                            status: row.status === '1' ? '0' : '1'
                        }).then(() => {
                            this.$Message.success('修改成功')
                            this.getData()
                        })
                    }
                });
            },
            // 切换分页
            handleChangePage (e) {
                this.page.page = e
                this.getData()
            },
            changePageSize (e) {
                this.page.pageSize = e
                this.getData()
            },
            // 编辑
            handleUpdata (index) {
                this.$nextTick(() => {
                    this.$refs['create'].resetFields();
                    this.updateIndex = index;
                    this.title = '编辑'
                    const item = this.dataList[index];
                    for (let key in this.formData) {
                        if (key === 'status') {
                            this.formData[key] = item[key] === '1';
                        } else {
                            this.formData[key] = item[key];
                        }
                    }
                    this.formData.id = item.id;
                    this.roleList(this.dataList[index].id)
                });
            },
            // 获取角色详情
            roleList (roleId) {
                this.showCreate = true;
                this.$nextTick(() => {
                    GetRolePermission({ id: roleId }).then(res => {
                        this.rolePermissionList = res.auth
                        this.$nextTick(() => {
                            this.handleSelectRoles()
                        })
                    })
                })
            },
            // 选择权限
            handleSelectRoles (val) {
                let checklist = this.$refs['roleTree'].getCheckedAndIndeterminateNodes();
                this.selectPermissonList = [];
                checklist.forEach(item => {
                    let resList = {};
                    resList.permission_id = item.value;
                    resList.permission_type = item.permission_type;
                    this.selectPermissonList.push(resList);
                });
                // 确定设置权限
            },
            // 提交
            handleSubmit () {
                this.$refs.create.validate(valid => {
                    if (valid) {
                        let menuIds = []
                        let actionIds = []
                        let moduleIds = []
                        if (this.selectPermissonList && this.selectPermissonList.length > 0) {
                            this.selectPermissonList.forEach((item) => {
                                if (item.permission_type === 0) {
                                    moduleIds.push(item.permission_id)
                                } else if (item.permission_type === 1) {
                                    menuIds.push(item.permission_id)
                                } else if (item.permission_type === 2) {
                                    actionIds.push(item.permission_id)
                                }
                            })
                        }
                        let sendData = JSON.parse(JSON.stringify(this.formData));
                        sendData.status = sendData.status === true ? '1' : '0';
                        sendData.menu_ids = menuIds.length > 0 ? menuIds.join(',') : ''
                        sendData.action_ids = actionIds.length > 0 ? actionIds.join(',') : ''
                        sendData.module_ids = moduleIds.length > 0 ? moduleIds.join(',') : ''
                        sendData.type = 2
                        if (this.updateIndex < 0) {
                            CreateRole(sendData).then(() => {
                                // 创建模块成功后，刷新页面
                                this.showCreate = false;
                                this.getData();
                                this.$Message.success('创建角色成功');
                            })
                        } else {
                            UpdateRole(sendData).then(() => {
                                this.showCreate = false;
                                this.getData();
                                this.$Message.success('修改角色成功');
                            })
                        }
                        this.creating = false;
                        this.$nextTick(() => {
                            this.creating = true;
                        });
                    } else {
                        this.creating = false;
                        this.$nextTick(() => {
                            this.creating = true;
                        });
                    }
                })
            }
        }
    }
</script>

<style scoped lang="less">
    .role-permission-modal {
        max-height: 400px;
        overflow: auto;
    }
    .shou{
        cursor: default;
    }
</style>
